package com.bogo.dbtable.controller;

import com.bogo.dbtable.modelVo.table.TableVo;
import com.bogo.dbtable.modelVo.result.ApiResult;
import com.bogo.dbtable.service.dbtable.domain.Field;
import com.bogo.dbtable.service.dbtable.domain.Table;
import com.bogo.dbtable.service.dbtable.serviceImpl.TableService;
import com.bogo.dbtable.tool.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.sql.SQLException;
import java.util.List;

/**
 * @Author: CHICHI
 * @Date: 2025-05-08-13:45
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/api/dbtable")
public class TableController {
    @Autowired
    private TableService tableService;
    @PostMapping("/create")
    public ApiResult createTable(@RequestBody Table table) throws SQLException {
        log.info("createTable:{}", table);
        ApiResult result=new ApiResult();
        TableVo tableVos=tableService.getTableBytableName(table.getTableName());
        if(tableVos!=null){
            result.setCode(1001);
            result.setMsg("该表已存在");
            return result;
        }else {
            tableService.createTable(table);
            result.setCode(200);
            result.setMsg("创建成功");
            return result;
        }
    }
    @GetMapping("/getTable")
    public ApiResult getTable() throws SQLException {
        List<TableVo> tables = tableService.getTable();
        return ApiResult.success(tables);
    }
    @PostMapping("/updateTable")
    public ApiResult updateTable(@RequestParam String tableName,@RequestParam String fieldName) throws SQLException {
        log.info("updateTable:{}", tableName,fieldName);
        tableService.updateTable(tableName,fieldName);
        return ApiResult.success();
    }
    @PostMapping("/newUpdateTable")
    public ApiResult newUpdateTable(@RequestParam String tableName,@RequestBody Field field) throws SQLException {
        log.info("updateTable:{}", tableName,field);
        tableService.newUpdateTable(tableName,field);
        return ApiResult.success();
    }
    @GetMapping("getTableBytableName")
    public ApiResult getTableBytableName(@RequestParam String tableName) throws SQLException {
        log.info("getTableBytableName:{}", tableName);
        TableVo table = tableService.getTableBytableName(tableName);
        return ApiResult.success(table);
    }
    @PostMapping("deleteTable")
    public ApiResult deleteTable(@RequestParam Integer id) throws SQLException {
        log.info("deleteTable:{}",  id );
        tableService.deleteTable(id);
        return ApiResult.success();
    }
}
